package com.cysyz.web.modules.base.support.filter;

import com.cysyz.web.modules.base.support.SysConstants;
import com.cysyz.web.modules.base.user.domain.SysUser;
import com.cysyz.web.modules.base.user.service.SysUserService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 如果当前session中没有用户，那么就自动进行登录。用于开发中，省去手动登录的麻烦。
 */
public class UserInjectFilter implements Filter {
    private String userName;
    private SysUserService sysUserService;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;

        HttpSession session=req.getSession();
        SysUser sysUser = (SysUser) session.getAttribute(SysConstants.CURRENT_LOGIN_SYSUSER);
        String loginName = userName;
        if (sysUser == null) {
            sysUser = sysUserService.getSysUserByUserName(loginName);
            session.setAttribute(SysConstants.CURRENT_LOGIN_SYSUSER, sysUser);
        }


        if (sysUser == null) {
            response.getWriter().print("there is no user with username ["+loginName+"], please config first");
        } else {
		    chain.doFilter(request, response);
        }

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
        userName = filterConfig.getInitParameter("userName");
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
        sysUserService = (SysUserService)wac.getBean("sysUserService");
	}

}
